package com.wanxi.spring.cloud.role.service.impl;

import com.wanxi.spring.cloud.commons.api.CommonResult;
import com.wanxi.spring.cloud.role.mapper.RoleMapper;
import com.wanxi.spring.cloud.role.model.Permission;
import com.wanxi.spring.cloud.role.model.Role;
import com.wanxi.spring.cloud.role.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 蒋帆
 * @since 2020-12-21
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired(required = false)
    RoleMapper roleMapper;

    @Override
    public CommonResult addRole(Role role) {
        role.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        role.setEnable("yes");
        int result = roleMapper.addRole(role);
        if (result > 0)
            return CommonResult.success(result, "添加成功");
        return CommonResult.failed("添加失败");
    }

    @Override
    public CommonResult getRoles(Integer page, Integer limit) {
        page = (page - 1) * limit;
        List<Role> roles = roleMapper.getRoles(page, limit).stream().map(role -> {
            List<Permission> rolePermissions = roleMapper.getRolePermissions(role.getId());
            role.setPermissions(rolePermissions);
            return role;
        }).collect(Collectors.toList());
        long count = roleMapper.getRolesCount();
        return CommonResult.success(roles, count);
    }

    @Override
    public CommonResult updateRole(Role role) {
        int result = roleMapper.updateRole(role);
        if (result > 0)
            return CommonResult.success(result, "修改成功");
        return CommonResult.failed("修改失败");
    }

    @Override
    public CommonResult deleteRole(Integer id) {
        int result = roleMapper.deleteRole(id);
        if (result > 0)
            return CommonResult.success(result, "删除成功");
        return CommonResult.failed("删除失败");
    }

    @Override
    public CommonResult getRoleList() {
        List<Role> roles = roleMapper.getRoleList();
        return CommonResult.success(roles);
    }
}
